package com.xxtx.trade.thread;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.enums.ExportEnum;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.bean.UrlInfosBaidu;
import com.xxtx.trade.sysUser.dto.BaiDuInfoDto;
import com.xxtx.trade.sysUser.dto.TradeSysRoleDto;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Data
public class DownloadBaiduInfoThread implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadAdminSimThread.class);

    private int count;
    private String url;
    private String id; // 每次下载时随机出的 id

    private String userId; // 用户id
//    private String agentId; // 这个可以用来在info表中查询

    //    private String role_id; // 用户角色，管理员与普通用户
    private int type; //1

    private BaiDuInfoDto baiDuInfoDto;

    @Override
    public void run() {
        Integer pageCount = count / 100000 + 1;
        TradeSysAgentMapper tradeSysAgentMapper = SpringUtil.getBean(TradeSysAgentMapper.class);
        CacheManager cacheManager = SpringUtil.getBean(CacheManager.class);
        FieldManageMapper fieldManageMapper = SpringUtil.getBean(FieldManageMapper.class);

        // 一次性把 imei 和 phone 对照表查询出来，不用查询那么多次
        List<ImeiToPhoneDto> imeiToPhoneDtos = tradeSysAgentMapper.selectImeiList();
        HashMap<String, String> map = new HashMap<>();
        for (ImeiToPhoneDto imeiToPhoneDto : imeiToPhoneDtos) {
            map.put(imeiToPhoneDto.getImei(), imeiToPhoneDto.getPhone());
        }

        Map<String, Object> hashMap = new HashMap<>();

        Workbook workbook = null;

        ExportParams params = new ExportParams();

        try {
            if (type == 1) {
                List<UrlInfosBaidu> users = null;
                // 查询，每次查询10w条数据
                for (int i = 1; i <= pageCount; i++) {
                    baiDuInfoDto.setPageNo((i - 1) * 100000);
                    if (i == pageCount) {
                        baiDuInfoDto.setPerPageNum(count % 100000);
                    } else {
                        baiDuInfoDto.setPerPageNum(100000);
                    }

                    // 按用户权限查询
//                    baiDuInfoDto.setAgentId();
                    users = tradeSysAgentMapper.selectExcelUrlInfosBaidu(baiDuInfoDto);
                    // 给user插入place字段
                    for (UrlInfosBaidu urlInfosBaidu:users){
//                        LOGGER.info(urlInfosBaidu.toString());
                        if (urlInfosBaidu.getPhone()==null)continue;
//                        LOGGER.info(urlInfosBaidu.getPhone());
                        Collection<Object> phone_list = new ArrayList<>();
                        phone_list.add(urlInfosBaidu.getPhone().substring(0, 7));
                        String aa = (String) cacheManager.hMGet("phoneOwnership2", phone_list).get(0);
                        if (aa==null){
                            urlInfosBaidu.setPlace("未入库地区");
                            continue;
                        }
                        urlInfosBaidu.setPlace(aa.split("_")[1]);
                    }

                    if (baiDuInfoDto.getUser_role().equals("2")) {
                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfosBaidu.class, users);
                        users.clear();
                    } else {
                        // 生成要导出的数据
                        List<Map<String, String>> resultList = new ArrayList<>();
                        // 生成导出的列名
                        List<ExcelExportEntity> entityList = new ArrayList<>();

//                        ExcelExportEntity agentNameEntity = new ExcelExportEntity("客户名称", "agentName");
//                        entityList.add(agentNameEntity);

                        // 查询可显示字段，创建列名
                        List<FieldManageDto> fieldManageDtos = fieldManageMapper.getList();
                        for (FieldManageDto fieldManageDto : fieldManageDtos) {
                            if (fieldManageDto.getStatus().equals("1")) {
                                if (fieldManageDto.getSource().equals("5")){
                                    ExcelExportEntity ele = new ExcelExportEntity(fieldManageDto.getName(), fieldManageDto.getName());
                                    entityList.add(ele);
                                }
                            }
                        }
                        // 装载数据
                        for (UrlInfosBaidu urlInfosBaidu: users){
                            Map<String, String> rowMap = new HashMap<>();
                            for (ExcelExportEntity excelExportEntity: entityList){
                                if (excelExportEntity.getKey().equals("agentName")){
                                    rowMap.put("agentName", urlInfosBaidu.getAgentName());
                                }
                                if (excelExportEntity.getKey().equals("urlName")){
                                    rowMap.put("urlName", urlInfosBaidu.getUrlName());
                                }
                                if (excelExportEntity.getKey().equals("phone")){
                                    rowMap.put("phone", urlInfosBaidu.getPhone());
                                }
                                if (excelExportEntity.getKey().equals("place")){
                                    rowMap.put("place", urlInfosBaidu.getPlace());
                                }
                                if (excelExportEntity.getKey().equals("createTime")){
                                    rowMap.put("createTime", urlInfosBaidu.getCreateTime());
                                }
                                if (excelExportEntity.getKey().equals("aid")){
                                    rowMap.put("aid", urlInfosBaidu.getAid());
                                }
                                if (excelExportEntity.getKey().equals("uid")){
                                    rowMap.put("uid", urlInfosBaidu.getUid());
                                }
                                if (excelExportEntity.getKey().equals("userId")){
                                    rowMap.put("userId", urlInfosBaidu.getUserId());
                                }
                                if (excelExportEntity.getKey().equals("clickId")){
                                    rowMap.put("clickId", urlInfosBaidu.getClickId());
                                }
                                if (excelExportEntity.getKey().equals("idfa")){
                                    rowMap.put("idfa", urlInfosBaidu.getIdfa());
                                }
                                if (excelExportEntity.getKey().equals("imeiMd5")){
                                    rowMap.put("imeiMd5", urlInfosBaidu.getImeiMd5());
                                }
                                if (excelExportEntity.getKey().equals("androidid")){
                                    rowMap.put("androidid", urlInfosBaidu.getAndroidid());
                                }
                                if (excelExportEntity.getKey().equals("androididMd5")){
                                    rowMap.put("androididMd5", urlInfosBaidu.getAndroididMd5());
                                }
                                if (excelExportEntity.getKey().equals("ip")){
                                    rowMap.put("ip", urlInfosBaidu.getIp());
                                }
                                if (excelExportEntity.getKey().equals("ua")){
                                    rowMap.put("ua", urlInfosBaidu.getUa());
                                }
                                if (excelExportEntity.getKey().equals("os")){
                                    rowMap.put("os", urlInfosBaidu.getOs());
                                }
                                if (excelExportEntity.getKey().equals("ts")){
                                    rowMap.put("ts", urlInfosBaidu.getTs());
                                }
                                if (excelExportEntity.getKey().equals("extInfo")){
                                    rowMap.put("extInfo", urlInfosBaidu.getExtInfo());
                                }
                                if (excelExportEntity.getKey().equals("macMd5")){
                                    rowMap.put("macMd5", urlInfosBaidu.getMacMd5());
                                }
                                if (excelExportEntity.getKey().equals("mac")){
                                    rowMap.put("mac", urlInfosBaidu.getMac());
                                }
                                if (excelExportEntity.getKey().equals("oaid")){
                                    rowMap.put("oaid", urlInfosBaidu.getOaid());
                                }
                                if (excelExportEntity.getKey().equals("oaidMd5")){
                                    rowMap.put("oaidMd5", urlInfosBaidu.getOaidMd5());
                                }
                                if (excelExportEntity.getKey().equals("combId")){
                                    rowMap.put("combId", urlInfosBaidu.getCombId());
                                }
                                if (excelExportEntity.getKey().equals("size")){
                                    rowMap.put("size", urlInfosBaidu.getSize());
                                }
                                if (excelExportEntity.getKey().equals("deeplinkUrl")){
                                    rowMap.put("deeplinkUrl", urlInfosBaidu.getDeeplinkUrl());
                                }
                                if (excelExportEntity.getKey().equals("bdVid")){
                                    rowMap.put("bdVid", urlInfosBaidu.getBdVid());
                                }
                                if (excelExportEntity.getKey().equals("wordid")){
                                    rowMap.put("wordid", urlInfosBaidu.getWordid());
                                }
                                if (excelExportEntity.getKey().equals("productid")){
                                    rowMap.put("productid", urlInfosBaidu.getProductid());
                                }
                            }
                            resultList.add(rowMap);
                        }
                        workbook = ExcelExportUtil.exportBigExcel(params, entityList, resultList);
                        resultList.clear();
                        users.clear();
                    }

                }
            }
//            workbook.write(new FileOutputStream("E:/download/" + url));
            workbook.write(new FileOutputStream("/root/develop/export/" + url));
            workbook.close();
            hashMap.put("state", ExportEnum.SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug("导出失败信息为" + e.getMessage());
            LOGGER.debug("导出失败信息为" + e.getLocalizedMessage());
            hashMap.put("state", ExportEnum.FAIL.getCode());
        }
        hashMap.put("id", id);
        Date date = new Date();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String LgTime = sdformat.format(date);
        hashMap.put("endTime", LgTime);
        tradeSysAgentMapper.updateExporeByid(hashMap);
    }
}






















